#include "cclientserverorder.h"
#include "globalStructs.h"
#include <QNetworkRequest>
#include <QUrl>
#include <QMessageBox>

CClientServerOrder::CClientServerOrder()
{
    m_commandID = CLIENT_SERVER_ORDER;
    m_ArgCount = 6; // for we have 6 factors not including the "command ID"
    m_networkAccessManager = new QNetworkAccessManager(this);
}

CClientServerOrder::~CClientServerOrder()
{
    delete m_networkAccessManager;

    if (m_pListReply != NULL)
        delete m_pListReply;
}


QList<QString>& CClientServerOrder::formInteresedItemList()
{
    m_interestedList.append(QString("Person ID"));
    m_interestedList.append(QString("Start Latitude"));
    m_interestedList.append(QString("Start Longitude"));
    m_interestedList.append(QString("end Latitude"));
    m_interestedList.append(QString("end Longitude"));
    m_interestedList.append(QString("Waiting Time Limits"));
    m_interestedList.append(QString("Command ID"));


    return m_interestedList;
}

QMultiMap<QString, QString>* CClientServerOrder::formResult()
{
    m_xmlString = QString::fromUtf8(m_pListReply->readAll());
    if ( m_xmlString.isEmpty() )
    {
        // no contents have been read or an error occures
        return NULL;
    }

    if(this->isReplyStringRight() == false)
    {
        return NULL;
    }

    this->formInteresedItemList();

    QDomElement root = m_pXMLDocument->documentElement();

    QDomElement element = root.firstChildElement("orders");

    if (!element.isNull())
    {
        QDomElement child = element.firstChildElement("order");

        while (!child.isNull())
        {
            m_peopleID =  child.attribute("id");
            m_result.insert(m_interestedList[0], m_peopleID);

            m_startLat = child.attribute("startLat");
            m_result.insert(m_interestedList[1], m_startLat);

            m_startLong = child.attribute("startLong");
            m_result.insert(m_interestedList[2], m_startLong);

            m_endLat = child.attribute("endLat");
            m_result.insert(m_interestedList[3], m_endLat);

            m_endLong = child.attribute("endLong");
            m_result.insert(m_interestedList[4], m_endLong);

            m_waitTime = child.attribute("waitingtime");
            m_result.insert(m_interestedList[5], m_waitTime);

            //lastly insert the command ID
            m_result.insert("Command ID", QString::number(m_commandID) );

            child = child.nextSiblingElement("order");
        }
    }

    return &m_result;
}






